package com.aihome.springbootjwt.utils;

import com.aihome.springbootjwt.constant.JWTConstant;
import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.Claim;
import com.auth0.jwt.interfaces.DecodedJWT;

import java.util.Calendar;
import java.util.Date;

/**
 * @ClassName JWTUtil
 * @Description JWT工具
 * @Author zhangjigang
 * @Date 2021/3/23 17:46
 * @Version 1.0.0
 */
public class JwtUtil {

    static int expiresTime = 7 * 24 * 60;

    /**
     * 创建token
     *
     * @param userId   签发对象：这个用户的id
     * @param userName 用户名
     * @return 返回token
     */
    public static String createToken(String userId, String userName) {

        Calendar nowTime = Calendar.getInstance();
        nowTime.add(Calendar.MINUTE, expiresTime);
        Date expiresDate = nowTime.getTime();

        return JWT.create()
                //签发对象
                .withAudience(userId)
                //发行时间
                .withIssuedAt(new Date())
                //有效时间
                .withExpiresAt(expiresDate)
                //载荷，附加参数
                .withClaim("userName", userName)
                //加密
                .sign(Algorithm.HMAC256(JWTConstant.SECRET));
    }

    /**
     * 检验合法性，其中secret参数就应该传入的是用户的id
     *
     * @param token
     */
    public static boolean verifyToken(String token) {
        try {
            Algorithm algorithm = Algorithm.HMAC256(JWTConstant.SECRET);
            JWTVerifier jwtVerifier = JWT.require(algorithm).build();
            DecodedJWT jwt = jwtVerifier.verify(token);
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
        return true;
    }

    /**
     * 获取签发对象
     */
    public static String getAudience(String token) {
        return JWT.decode(token).getAudience().get(0);
    }

    /**
     * 通过载荷名字获取载荷的值
     */
    public static Claim getClaimByName(String token, String name) {
        return JWT.decode(token).getClaim(name);
    }

    public static void main(String[] args) {
        String userId = "1";
        String userName = "yonghu";
        System.out.println(JwtUtil.createToken(userId, userName));
    }
}
